package br.com.biavan.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.biavan.dao.AlunoDAO;
import br.com.biavan.model.Aluno;

/**
 * Servlet implementation class AlunoServlet
 */
@WebServlet("/AlunoServlet")
public class AlunoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AlunoServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		int acao = 0;
		
		try {
			acao = Integer.parseInt(request.getParameter("acao"));
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		switch(acao)
		{
		case 1: // inserir
			inserirAluno(request, response);
			break;
			
		case 2: // alterar
			// TODO: altera dados do aluno
			break;
			
		case 3: // exluir
			// TODO: exclui dados do aluno
			break;
			
		case 4: // buscar
			// TODO: busca por aluno
			break;
			
		default:
			listarAluno(request, response);
			break;
		}
		
	}

	private void inserirAluno(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		Aluno aluno = new Aluno();
		aluno.setNome(request.getParameter("nome"));
		aluno.setLogin(request.getParameter("login"));
		aluno.setEmail(request.getParameter("email"));
		aluno.setSenha(request.getParameter("senha"));

		AlunoDAO dao = new AlunoDAO(); 
		
		if (dao.inserir(aluno)) {
			request.setAttribute("mensagem", "Cadastrado com sucesso!");
			RequestDispatcher rd = request.getRequestDispatcher("messagesPages/sucesso.jsp");
			rd.forward(request, response);
		} else {
			request.setAttribute("mensagem", "Não foi possível cadatrar o aluno!");
			RequestDispatcher rd = request.getRequestDispatcher("messagesPages/falha.jsp");
			rd.forward(request, response);
		}

	}
	
	private void listarAluno(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		AlunoDAO dao = new AlunoDAO();
		
		request.setAttribute("alunos", dao.listar());
		RequestDispatcher rd = request.getRequestDispatcher("aluno/listar_aluno.jsp");
		rd.forward(request, response);
		
	}
	
}
